package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.*;
import io.minio.errors.MinioException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
//@RefreshScope
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;


    /**
     * 文件上传
     * @return
     */
    @Operation(summary = "文件上传")
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file){
        //  定义上传图片返回地址：
        String url="";
        //  获取到上传文件的信息：spring-mvc
        //  调用服务层方法.
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioConstantProperties.getEndpointUrl())
                            .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket "+minioConstantProperties.getBucketName()+" already exists.");
            }

            //  文件名： atguigu.jpg
            String fileName = UUID.randomUUID().toString().replaceAll("-","")+ "."+ FilenameUtils.getExtension(file.getOriginalFilename());
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            //  实现url 地址拼接： http://192.168.200.130:9000/atguigutss/3530012ac40e4b11969fb26aa4f09666.jpg
            //  http://192.168.200.130:9000
            url = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName()+"/"+fileName;
            System.out.println("文件上传url:"+url);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }

        //  返回数据
        return Result.ok(url);
    }

    public static void main(String[] args) {
        String str="atguigu.jpg";
        //  第一种方式：直接字符串截取. substring(); lastIndexOf();
        System.out.println(str.lastIndexOf("."));
        System.out.println(str.substring(str.lastIndexOf(".")));

        System.out.println(FilenameUtils.getExtension(str));


    }

}
